import axios from 'axios';
import configs from './configs';
import router from '@/router';
import { ElNotification, ElMessage } from 'element-plus';
import * as NProgress from 'nprogress';

import { useStorage } from '@vueuse/core';
const token = useStorage<string | undefined>('token', '');

const request = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: configs.API_BASE_URL,
  // baseURL: process.env.NODE_ENV == 'development' ? '/api' : '',
  // 超时
  timeout: configs.API_TIMEOUT
});

// 请求拦截器
request.interceptors.request.use(
  (config: any) => {
    // 给每个接口插入token
    if (token && token.value) {
      config.headers['Authorization'] = `Bearer ${token.value}`;
    }

    // 给每个请求附带进度条
    NProgress.start();

    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (res) => {
    // 结束进度条
    NProgress.done();
    // 返回所有数据
    return res.data;
  },
  (error) => {
    // 结束进度条
    NProgress.done();

    const { response } = error;

    // token失效
    if (response.status == 401) {
      token.value = null;
      ElNotification({
        title: 'Token失效',
        message: '单次登录Token已失效，请重新登录！',
        duration: 0,
        type: 'error'
      });
      router.push({ path: '/login' });
    }
    // 权限不足
    else if (response.status == 403) {
      token.value = null;
      ElNotification({
        title: '权限不足，请联系管理员',
        message: response.data?.message,
        duration: 0,
        type: 'error'
      });
      router.push({ path: '/login' });
    } else {
      const message = response.data?.message ?? response.message;
      ElMessage.error(message);
    }

    return Promise.reject(response.data ?? response);
  }
);

export default request;
